﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using DataBase;
using SDF.Core;
using NUnit.Framework;
using SDFAuth;

namespace Nop.Data.Tests
{
    [TestFixture]
    public abstract class PersistenceTest<T> where T : BaseDbContext, new()
    {
        protected T context;

        [SetUp]
        public void SetUp()
        {
            context = GetDbInstance();
        }

        /// <summary>
        /// Persistance test helper
        /// </summary>
        /// <typeparam name="T">Entity type</typeparam>
        /// <param name="entity">Entity</param>
        /// <param name="disposeContext">A value indicating whether to dispose context</param>
        protected T SaveAndLoadEntity<T>(T entity, bool disposeContext = true) where T : BaseEntity
        {

            context.Set<T>().Add(entity);
            context.SaveChanges();

            var id = Convert.ToInt32(GetPropertyValue(entity, "id"));

            if (disposeContext)
            {
                context.Dispose();
                context = GetDbInstance();
            }

            var fromDb = context.Set<T>().Find(id);
            return fromDb;
        }
        private T GetDbInstance()
        {
            //context = new SDFAuthEntities(AppSettings.SDFAuthConn);
           var  c= new T();
            return c;
        }
        /// <summary>
        /// 获取一个类指定的属性值
        /// </summary>
        /// <param name="info">object对象</param>
        /// <param name="field">属性名称</param>
        /// <returns></returns>
        private static object GetPropertyValue(object info, string field)
        {
            if (info == null) return null;
            Type t = info.GetType();
            IEnumerable<System.Reflection.PropertyInfo> property = from pi in t.GetProperties() where pi.Name.ToLower() == field.ToLower() select pi;
            return property.First().GetValue(info, null);
        }
    }
}
